<template>
  <div class="tabs" :class="tabsClasses">
    <!-- Header -->
    <div class="tabs__header">
      <h2 class="tabs__title">聊天列表</h2>
      <div class="tabs__actions">
        <button
          @click="handleSearch"
          class="action-button"
          title="搜索聊天"
        >
          <span class="icon">🔍</span>
        </button>
        <button
          @click="handleNewChat"
          class="action-button action-button--primary"
          title="新建聊天"
        >
          <span class="icon">➕</span>
        </button>
      </div>
    </div>

    <!-- Search Bar -->
    <div v-if="showSearch" class="tabs__search">
      <div class="search-input-wrapper">
        <input
          ref="searchInput"
          v-model="searchQuery"
          type="text"
          placeholder="搜索聊天..."
          class="search-input"
          @keydown.escape="hideSearch"
        />
        <button
          @click="hideSearch"
          class="search-close"
        >
          ✕
        </button>
      </div>
    </div>

    <!-- Chat List -->
    <div class="tabs__list" :class="{ 'tabs__list--searching': showSearch }">
      <div v-if="loading" class="tabs__loading">
        <div class="loading-skeleton" v-for="i in 5" :key="i">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-line skeleton-line--name"></div>
            <div class="skeleton-line skeleton-line--message"></div>
          </div>
        </div>
      </div>

      <div v-else-if="filteredChatList.length === 0" class="tabs__empty">
        <div class="empty-state">
          <span class="empty-icon">💬</span>
          <h3 class="empty-title">
            {{ searchQuery ? '未找到匹配的聊天' : '暂无聊天记录' }}
          </h3>
          <p class="empty-description">
            {{ searchQuery ? '尝试使用其他关键词搜索' : '点击右上角的 + 按钮开始新的聊天' }}
          </p>
          <button
            v-if="!searchQuery"
            @click="handleNewChat"
            class="empty-action"
          >
            开始聊天
          </button>
        </div>
      </div>

      <div v-else class="chat-list">
        <div
          v-for="chat in filteredChatList"
          :key="chat.id"
          @click="handleChatSelect(chat.id)"
          :class="[
            'chat-item',
            { 'chat-item--active': activeChat === chat.id }
          ]"
        >
          <!-- Avatar -->
          <div class="chat-avatar">
            <img
              :src="chat.avatar"
              :alt="chat.name"
              class="avatar-image"
              @error="handleAvatarError"
            />
            <div
              v-if="chat.status === 'online'"
              class="status-indicator status-indicator--online"
            ></div>
            <div
              v-else-if="chat.status === 'away'"
              class="status-indicator status-indicator--away"
            ></div>
          </div>

          <!-- Content -->
          <div class="chat-content">
            <div class="chat-header">
              <h3 class="chat-name">{{ chat.name }}</h3>
              <span class="chat-time">{{ formatTime(chat.timestamp) }}</span>
            </div>
            <div class="chat-preview">
              <p class="chat-message">{{ chat.lastMessage }}</p>
              <div
                v-if="chat.unreadCount > 0"
                class="unread-badge"
              >
                {{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
              </div>
            </div>
          </div>

          <!-- Context Menu Trigger -->
          <button
            @click.stop="handleContextMenu(chat.id, $event)"
            class="context-menu-trigger"
            title="更多操作"
          >
            ⋯
          </button>
        </div>
      </div>
    </div>

    <!-- Context Menu -->
    <div
      v-if="contextMenu.visible"
      ref="contextMenuRef"
      class="context-menu"
      :style="contextMenuStyle"
    >
      <button
        v-for="action in contextMenuActions"
        :key="action.id"
        @click="handleContextAction(action.id)"
        class="context-menu-item"
        :class="{ 'context-menu-item--danger': action.danger }"
      >
        <span class="menu-icon">{{ action.icon }}</span>
        <span class="menu-label">{{ action.label }}</span>
      </button>
    </div>

    <!-- Overlay for context menu -->
    <div
      v-if="contextMenu.visible"
      class="context-overlay"
      @click="hideContextMenu"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useUI } from '@/composables'
import type { TabsProps, ChatItem } from '@/types'
import { formatTimestamp } from '@/utils'

// Props
defineProps<TabsProps>()

// Emits
const emit = defineEmits<{
  chatSelect: [chatId: string]
}>()

// Composables
const ui = useUI()

// Refs
const searchInput = ref<HTMLInputElement>()
const contextMenuRef = ref<HTMLElement>()

// State
const showSearch = ref(false)
const searchQuery = ref('')
const loading = ref(false)
const contextMenu = ref({
  visible: false,
  chatId: '',
  x: 0,
  y: 0
})

// Computed
const tabsClasses = computed(() => ({
  'tabs--mobile': ui.isMobile,
  'tabs--dark': ui.theme === 'dark'
}))

const filteredChatList = computed(() => {
  if (!searchQuery.value) return props.chatList
  
  const query = searchQuery.value.toLowerCase()
  return props.chatList.filter(chat =>
    chat.name.toLowerCase().includes(query) ||
    chat.lastMessage.toLowerCase().includes(query)
  )
})

const contextMenuStyle = computed(() => ({
  left: `${contextMenu.value.x}px`,
  top: `${contextMenu.value.y}px`
}))

const contextMenuActions = computed(() => [
  {
    id: 'pin',
    label: '置顶聊天',
    icon: '📌',
    danger: false
  },
  {
    id: 'mute',
    label: '静音通知',
    icon: '🔕',
    danger: false
  },
  {
    id: 'archive',
    label: '归档聊天',
    icon: '📦',
    danger: false
  },
  {
    id: 'delete',
    label: '删除聊天',
    icon: '🗑️',
    danger: true
  }
])

// Methods
const handleChatSelect = (chatId: string) => {
  emit('chatSelect', chatId)
}

const handleSearch = async () => {
  showSearch.value = true
  await nextTick()
  searchInput.value?.focus()
}

const hideSearch = () => {
  showSearch.value = false
  searchQuery.value = ''
}

const handleNewChat = () => {
  ui.openModal('createChat')
}

const formatTime = (timestamp: Date): string => {
  return formatTimestamp(timestamp)
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/default-avatar.png'
}

const handleContextMenu = (chatId: string, event: MouseEvent) => {
  event.preventDefault()
  contextMenu.value = {
    visible: true,
    chatId,
    x: event.clientX,
    y: event.clientY
  }
}

const hideContextMenu = () => {
  contextMenu.value.visible = false
}

const handleContextAction = (actionId: string) => {
  const chatId = contextMenu.value.chatId
  
  switch (actionId) {
    case 'pin':
      // TODO: Implement pin chat
      console.log('Pin chat:', chatId)
      break
    case 'mute':
      // TODO: Implement mute chat
      console.log('Mute chat:', chatId)
      break
    case 'archive':
      // TODO: Implement archive chat
      console.log('Archive chat:', chatId)
      break
    case 'delete':
      // TODO: Implement delete chat
      if (confirm('确定要删除这个聊天吗？')) {
        console.log('Delete chat:', chatId)
      }
      break
  }
  
  hideContextMenu()
}

const handleClickOutside = (event: MouseEvent) => {
  if (contextMenu.value.visible && contextMenuRef.value) {
    if (!contextMenuRef.value.contains(event.target as Node)) {
      hideContextMenu()
    }
  }
}

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    if (contextMenu.value.visible) {
      hideContextMenu()
    } else if (showSearch.value) {
      hideSearch()
    }
  }
}

// Lifecycle
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.tabs {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--color-background-light);
  border-right: 1px solid var(--color-border);
}

.tabs--dark {
  background-color: #2a2a2a;
  border-right-color: #404040;
}

/* Header */
.tabs__header {
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--color-border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: var(--color-surface);
}

.tabs--dark .tabs__header {
  background-color: #1e1e1e;
  border-bottom-color: #404040;
}

.tabs__title {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  margin: 0;
}

.tabs__actions {
  display: flex;
  gap: var(--spacing-sm);
}

.action-button {
  width: 32px;
  height: 32px;
  border: none;
  background: var(--color-surface-hover);
  color: var(--color-text-secondary);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}

.action-button:hover {
  background: var(--color-surface-active);
  color: var(--color-text-primary);
}

.action-button--primary {
  background: var(--color-primary);
  color: var(--color-text-inverse);
}

.action-button--primary:hover {
  background: var(--color-primary-dark);
}

.action-button .icon {
  font-size: var(--font-size-sm);
}

/* Search */
.tabs__search {
  padding: var(--spacing-md) var(--spacing-lg);
  border-bottom: 1px solid var(--color-border);
  background-color: var(--color-surface);
}

.tabs--dark .tabs__search {
  background-color: #1e1e1e;
  border-bottom-color: #404040;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-input {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  padding-right: 32px;
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-md);
  background-color: var(--color-background);
  color: var(--color-text-primary);
  font-size: var(--font-size-sm);
  transition: border-color var(--transition-fast);
}

.search-input:focus {
  outline: none;
  border-color: var(--color-primary);
}

.search-close {
  position: absolute;
  right: var(--spacing-sm);
  width: 20px;
  height: 20px;
  border: none;
  background: none;
  color: var(--color-text-secondary);
  cursor: pointer;
  border-radius: var(--border-radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--font-size-xs);
  transition: all var(--transition-fast);
}

.search-close:hover {
  background: var(--color-surface-hover);
  color: var(--color-text-primary);
}

/* List */
.tabs__list {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-sm) 0;
}

.tabs__list--searching {
  padding-top: 0;
}

/* Loading */
.tabs__loading {
  padding: var(--spacing-md);
}

.loading-skeleton {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

.skeleton-avatar {
  width: 48px;
  height: 48px;
  border-radius: var(--border-radius-full);
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-line {
  height: 12px;
  border-radius: var(--border-radius-sm);
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  margin-bottom: var(--spacing-xs);
}

.skeleton-line--name {
  width: 60%;
}

.skeleton-line--message {
  width: 80%;
}

.tabs--dark .skeleton-avatar,
.tabs--dark .skeleton-line {
  background: linear-gradient(90deg, #404040 25%, #505050 50%, #404040 75%);
  background-size: 200% 100%;
}

@keyframes loading {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* Empty State */
.tabs__empty {
  padding: var(--spacing-2xl);
  text-align: center;
}

.empty-state {
  max-width: 200px;
  margin: 0 auto;
}

.empty-icon {
  font-size: 48px;
  display: block;
  margin-bottom: var(--spacing-lg);
  opacity: 0.5;
}

.empty-title {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.empty-description {
  font-size: var(--font-size-sm);
  color: var(--color-text-secondary);
  margin: 0 0 var(--spacing-lg) 0;
  line-height: var(--line-height-relaxed);
}

.empty-action {
  padding: var(--spacing-sm) var(--spacing-lg);
  border: none;
  background: var(--color-primary);
  color: var(--color-text-inverse);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  transition: background-color var(--transition-fast);
}

.empty-action:hover {
  background: var(--color-primary-dark);
}

/* Chat List */
.chat-list {
  padding: 0;
}

.chat-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md) var(--spacing-lg);
  cursor: pointer;
  transition: background-color var(--transition-fast);
  position: relative;
  border-left: 3px solid transparent;
}

.chat-item:hover {
  background-color: var(--color-surface-hover);
}

.chat-item--active {
  background-color: var(--color-surface-active);
  border-left-color: var(--color-primary);
}

.chat-avatar {
  position: relative;
  flex-shrink: 0;
}

.avatar-image {
  width: 48px;
  height: 48px;
  border-radius: var(--border-radius-full);
  object-fit: cover;
  border: 2px solid var(--color-border-light);
}

.status-indicator {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 12px;
  height: 12px;
  border-radius: var(--border-radius-full);
  border: 2px solid var(--color-surface);
}

.status-indicator--online {
  background-color: var(--color-success);
}

.status-indicator--away {
  background-color: var(--color-warning);
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--spacing-xs);
}

.chat-name {
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-time {
  font-size: var(--font-size-xs);
  color: var(--color-text-muted);
  flex-shrink: 0;
  margin-left: var(--spacing-sm);
}

.chat-preview {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-message {
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.unread-badge {
  background-color: var(--color-primary);
  color: var(--color-text-inverse);
  font-size: 10px;
  font-weight: var(--font-weight-bold);
  padding: 2px 6px;
  border-radius: var(--border-radius-full);
  min-width: 18px;
  text-align: center;
  margin-left: var(--spacing-sm);
  flex-shrink: 0;
}

.context-menu-trigger {
  position: absolute;
  top: var(--spacing-sm);
  right: var(--spacing-sm);
  width: 24px;
  height: 24px;
  border: none;
  background: none;
  color: var(--color-text-muted);
  cursor: pointer;
  border-radius: var(--border-radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all var(--transition-fast);
}

.chat-item:hover .context-menu-trigger {
  opacity: 1;
}

.context-menu-trigger:hover {
  background: var(--color-surface-hover);
  color: var(--color-text-primary);
}

/* Context Menu */
.context-menu {
  position: fixed;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  z-index: var(--z-popover);
  min-width: 160px;
  padding: var(--spacing-xs) 0;
}

.tabs--dark .context-menu {
  background: #2a2a2a;
  border-color: #404040;
}

.context-menu-item {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  background: none;
  color: var(--color-text-primary);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-size: var(--font-size-sm);
  text-align: left;
  transition: background-color var(--transition-fast);
}

.context-menu-item:hover {
  background: var(--color-surface-hover);
}

.context-menu-item--danger {
  color: var(--color-error);
}

.context-menu-item--danger:hover {
  background: rgba(239, 68, 68, 0.1);
}

.menu-icon {
  font-size: var(--font-size-sm);
  width: 16px;
  text-align: center;
}

.menu-label {
  flex: 1;
}

.context-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: calc(var(--z-popover) - 1);
}

/* Mobile adjustments */
.tabs--mobile {
  border-right: none;
}

.tabs--mobile .tabs__header {
  padding: var(--spacing-md);
}

.tabs--mobile .chat-item {
  padding: var(--spacing-md);
}

.tabs--mobile .avatar-image {
  width: 40px;
  height: 40px;
}

/* Scrollbar */
.tabs__list::-webkit-scrollbar {
  width: 6px;
}

.tabs__list::-webkit-scrollbar-track {
  background: var(--color-background-light);
}

.tabs__list::-webkit-scrollbar-thumb {
  background: var(--color-border-dark);
  border-radius: var(--border-radius-full);
}

.tabs__list::-webkit-scrollbar-thumb:hover {
  background: var(--color-secondary);
}
</style>